import re
from django_redis import get_redis_connection

from rest_framework import serializers

# serializers.Serializer
# serializers.ModelSerializer
# 由于对数据库进行了增加操作，所以使用ModelSerializer自动实现了create()方法和update()方法
from users.models import User


class RegisterCreateUserSerializer(serializers.ModelSerializer):
    # 获取到username,password,password2,sms_code,allow,mobile

    # 调用序列化器进行校验
    # 单个字段验证：手机号是否正确，allow
    # 多个字段验证：password2和password,sms_code和redis里存储的sms_code
    # 入库
    # fields 是根据ModelSerialiser自动生成的字段，对于模型没有的字段需要手动添加
    # write_only 只能写入，而且在反序列化的时候必须写入
    # required  序列化，反序列化的时候都必须写入，


    password2 = serializers.CharField(label="确认密码",write_only=True,
                                      allow_null=False,allow_blank=False)

    sms_code = serializers.CharField(label="短信验证码",write_only=True,
                                     max_length=6,min_length=6)

    allow = serializers.CharField(label='是否同意协议',write_only=True,
                                  allow_blank=False,allow_null=False)

    token = serializers.CharField(label="进行序列化操作返回的token",read_only=True)

    class Meta:
        model = User
        fields = ["id",'username','password','mobile','password2','sms_code','allow',"token"]


#     选项校验
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

#    单个字段验证
    def validate_mobile(self,value):

        if not re.match(r'1[3456789]\d{9}',value):
            raise serializers.ValidationError("验证码输入错误")


        return value


    def validate_allow(self,value):

        if value != 'true':
            raise serializers.ValidationError("请同意协议谢谢")
        return value


#   多个字段验证
    def validate(self, attrs):

        password = attrs.get('password')
        password2 = attrs.get("password2")
        sms_code = attrs.get('sms_code')
        mobile = attrs.get("mobile")

        if password != password2:
            raise serializers.ValidationError('密码输入不一致')


        redis_conn = get_redis_connection("code")

        redis_code = redis_conn.get('sms_%s'%mobile)

        if redis_code is None:
            raise serializers.ValidationError('短信验证码过期')

        if redis_code.decode() != sms_code:
            raise serializers.ValidationError("短信验证码输入错误")

        return attrs


#   父类的create()方法将password2，allow，sms_code方法入库
#   不能满足我们的需求，所以进行重写

    def create(self, validated_data):

        print(validated_data)
#   现在的validated_date 有6个字段，删除多余字段
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

#         删除多余字段后入库
        user = User.objects.create(**validated_data)

        # 密码需要加密方法继承自djang自带模型类
        user.set_password(validated_data['password'])
        # 保存
        user.save()

        # 在创建了一个用户之后，生成一个token返回
        from rest_framework_jwt.settings import api_settings

        # 获取2个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 调用这2个方法
        # 把用户的信息给payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 把token信息传递给user
        # 进行序列化操作的时候把token返回给浏览器

        user.token = token


        return user



class UserCenterInfoSerializer(serializers.ModelSerializer):


    class Meta:
        model = User
        fields = ['id','username','mobile','email','email_active']



class EmailUpdateSerializer(serializers.ModelSerializer):


    class Meta:
        model = User
        fields = ['id', 'email']

        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    # 更新用户的邮箱信息
    def update(self, instance, validated_data):

        email = validated_data.get('email')

        instance.email = email

        instance.save()

        from django.core.mail import send_mail
        from django.conf import settings
        # subject, 主题
        subject = "美多商城激活邮件e"
        #  message,普通邮件正文
        message = ''
        #  from_email,发件人
        from_email = settings.EMAIL_FROM
        #  recipient_list, 收件人列表
        recipient_list = [email]
        # html_message=None 多媒体邮件正文，可以是html字符串
        # html_message = '<p>尊敬的用户您好！</p>'

        # 生成一个对id,email进行处理的url

        verify_url = instance.generice_active_url()


        html_message =  '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject,message,from_email,recipient_list,html_message=html_message)

        from celery_tasks.email.tasks import send_verify_email

        send_verify_email.delay(subject,message,from_email,recipient_list,html_message=html_message)





        return instance




from goods.models import SKU
class UserHistorySerilizer(serializers.Serializer):

    sku_id = serializers.CharField(label="商品id",required=True)

    def validate_sku_id(self,value):

        try:
            SKU.objects.get(pk=value)

        except SKU.DoesNotExist:
            serializers.ValidationError("商品信息不存在")

        return value

    #  重写save 方法,将数据保存在redis中

    def create(self, validated_data):

        # 我们记录用户记录的时候, key 确保用户记录的唯一性
        # history_id
        user = self.context["request"].user
        sku_id = validated_data.get("sku_id")

        # 链接redis
        redis_conn = get_redis_connection("history")

        # 2. 保存在列表中,先把重复的删除
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        # 3. 再添加数据
        redis_conn.lpush('history_%s' % user.id, sku_id)
        # 4.只保留5条记录就可以(Redis保留不能太多的数据)
        redis_conn.ltrim('history_%s' % user.id, 0, 4)


        return validated_data


from goods.models import SKU
class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')





from .models import Address

class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)



















